import {
	hexMD5
} from './md5';

import {
	toLogin,
	loadToShow,
	loadToHide,
	errorToShow
} from './common.js'
import {
	baseUrl
} from './config.js'
var loadding
//不带Token的post请求
const httpRequest = (opts) => {
	try {
		uni.showLoading({
			title: '加载中'
		});
		let timestamp = new Date().getTime();
		let httpDefaultOpts = {
			url: baseUrl + opts.url,
			data: opts.data,
			method: 'POST',
			header: {
				'sign': getSign(true, timestamp),
				'timestamp': timestamp,
				// "Content-Type" : "application/x-www-form-urlencoded"
				
			},
			dataType: 'json',
		}
		let promise = new Promise(function(resolve, reject) {
			uni.request(httpDefaultOpts).then(
				(response) => {
					
					
					const res = response[1].data
					
					if (res.code!==0) {
						uni.showToast({
							title: res.Message,
							icon: 'none',
							duration: 2000
						});
						//如果是code是401 清楚登录状态
						if (response[1].statusCode == 401) {
							uni.clearStorage();
							uni.reLaunch({
								url: '../pages/login/index'
							})
						}
						reject('error')
					} else {
						if(res.Data){
							resolve(res.Data)
						}else{
							resolve(res.data)
						}
						
					}
				}
			).catch(
				(response) => {
					reject(response)
				}
			)
		})
		return promise
	} finally {
		
		setTimeout(function() {
			uni.hideLoading();
		}, 300);
	}
};

function getSign(ignoreToken, timestamp) {
	let token = ''
	if (!ignoreToken) {
		token = uni.getStorageSync('userToken');
	}
	return hexMD5(token + timestamp + "GreenTree")
}

function pushLogin() {
	uni.reLaunch({
		url: '../pages/login/index'
	})
}

//带Token的post请求
const httpTokenRequest = (opts) => {
	uni.showLoading({
		title: '加载中'
	});
	let token = "";
	token = uni.getStorageSync('userToken');
	let timestamp = new Date().getTime();
	//此token是登录成功后后台返回保存在storage中的
	let httpDefaultOpts = {
		url: baseUrl + opts.url,
		data: opts.data,
		method: 'POST',
		header: {
			'sign': getSign(false, timestamp),
			'timestamp': timestamp,
			'satoken': token
		},
		dataType: 'json',
	}
	try {
		let promise = new Promise(function(resolve, reject) {
			uni.request(httpDefaultOpts).then(
				(response) => {
					if (response[1].statusCode == 401) {
						toLogin()
						reject('error')
						return;
					}
					const res = response[1].data
					if (!res.IsSuccess) {
						uni.showToast({
							title: res.Message,
							icon: 'none',
							duration: 2000
						});
						reject('error')
					} else {
						resolve(res.Data)
					}
				}
			).catch(
				(response) => {
					reject(response)
				}
			)
		})
		setTimeout(function() {
			uni.hideLoading();
		}, 500);
		return promise
	} finally {
		setTimeout(function() {
			uni.hideLoading();
		}, 500);
	}
};

//带Token的post请求
const httpTokenRequestSpecial = (opts) => {
	let token = "";
	token = uni.getStorageSync('userToken');
	let timestamp = new Date().getTime();
	//此token是登录成功后后台返回保存在storage中的
	let httpDefaultOpts = {
		url: baseUrl + opts.url,
		data: opts.data,
		method: 'POST',
		header: {
			'sign': getSign(false, timestamp),
			'timestamp': timestamp,
			'satoken': token
		},
		dataType: 'json',
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(httpDefaultOpts).then(
			(response) => {
				const res = response[1].data
				if (!res.IsSuccess) {
					uni.showToast({
						title: res.Message,
						icon: 'none',
						duration: 2000
					});
					//如果是code是401 清楚登录状态
					if (response[1].statusCode == 401) {
						uni.clearStorage();
						uni.reLaunch({
							url: '../pages/login/index'
						})
					}
					reject('error')
				} else {
					resolve(res.Message)
				}
			}
		).catch(
			(response) => {
				reject(response)
			}
		)
	})
	return promise
};

//Get请求
const httpRequestGet = (url, callback) => {
	
	uni.showLoading({
		title: '加载中'
	});
	uni.request({
		url: baseUrl + url,
		header: {
			'Accept': 'application/json',
			'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
		},
		method: 'GET',
		success: (response) => {
			 console.log(response,'this.response')
			uni.hideLoading();
			callback(response.data);
		},
		fail: (error) => {
			uni.hideLoading();
			if (error && error.response) {
				errorToShow(error.response);
			}
		},
		complete: (response) => {
			 console.log(response,'response2')
			setTimeout(function() {
				uni.hideLoading();
			}, 250);
		}
	});
}
//Get带token请求
const httptokenRequestGet = (url, callback) => {
	 console.log(url,'this.url')
	let token = "";
	token = uni.getStorageSync('userToken');
	uni.showLoading({
		title: '加载中'
	});
	uni.request({
		url: baseUrl + url.url,
		header: {
			'satoken': token,
			// 'Accept': 'application/json',
			'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
		},
		method: 'GET',
		dataType: 'json',
		success: (response) => {
			 console.log(response,'this.response')
			uni.hideLoading();
			callback(response.data);
		},
		fail: (error) => {
			uni.hideLoading();
			if (error && error.response) {
				errorToShow(error.response);
			}
		},
		complete: (response) => {
			 console.log(response,'response2')
			setTimeout(function() {
				uni.hideLoading();
			}, 250);
		}
	});
}


	const requestAll =(url, method = "GET", postData = {}, isForm = true, showLoading = true,type=1) =>{
		//接口请求
		 var that=this
		 let token = "";
		 token = uni.getStorageSync('userToken');
		 	let timestamp = new Date().getTime();
		if (showLoading) {
			uni.showLoading({
				mask: true,
				title: '请稍候...',
				success(res) {
					loadding = true
				}
			})
		}

			
		return new Promise((resolve, reject) => {
			uni.request({
				url:  baseUrl+url,
				data: postData,
				header: {
					'sign': getSign(false, timestamp),
					'timestamp': timestamp,
					'content-type': isForm ? 'application/x-www-form-urlencoded' : 'application/json',
					'Satoken':token?token:''
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					if(res.data.code==401){
						// uni.showModal({
						// 	title: '提示',
						// 	content: '登录状态已过期，请退出登录',
						// 	showCancel: false,
						// 	success: function (res) {
						// 		if (res.confirm) {
						// 			uni.clearStorage()
						// 			setTimeout(()=>{
						// 				uni.reLaunch({
						// 					url:"/pages/login/login"
						// 				})
						// 			},200)
									
						// 		} else if (res.cancel) {
						// 			console.log('用户点击取消');
						// 		}
						// 	}
						// });
					}else{
						if(res.data && res.data.data){
							let data = res.data.data;
							try{
								if(typeof data == 'string'){
									res.data.data  =JSON.parse(data)
								}
							}catch(e){
								res.data.data =data;
							}
						}
						resolve(res.data)
					}
					
				},
				fail: (error) => {
					errorToShow(error.response);
					reject(res)
				},
				complete: (res) => {
					if (loadding) {
						uni.hideLoading()
						loadding=false
					}
				}
			})
		})
	}
export default {
	baseUrl,
	httpRequest,
	httpTokenRequest,
	httpRequestGet,
	httptokenRequestGet,
	httpTokenRequestSpecial,
	requestAll
}
